#include "Mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>

#define FILE_MODE 0666

_FILE *_fopen(const char *filename, const char *flag){
    assert(filename);
    assert(flag);

    int f=0;
    int fd=-1;

    if(strcmp(flag,"w") == 0){
        f = (O_CREAT|O_WRONLY|O_TRUNC);
        fd = open(filename, f, FILE_MODE);
    }
    else if(strcmp(flag,"a") == 0){
        f = (O_CREAT|O_WRONLY|O_APPEND);
        fd = open(filename, f, FILE_MODE);
    }
    else if(strcmp(flag,"r") == 0){
        f = O_RDONLY;
        fd = open(filename, f);
    }
    else {
        return NULL;
    }

    if(fd == -1) return NULL;

    //创建_FILE对象
    _FILE *fp = (_FILE*)malloc(sizeof(_FILE));
    if(fp == NULL) return NULL;

    fp->fileno = fd;

    //设置刷新方式
    fp->flag = FLUSH_ALL;
    //更新指针
    fp->out_pos = 0;

    return fp;
}

int _fwrite(_FILE *fp, const char *s, int len){
    assert(fp);

    //先将写入的内容拷贝到缓冲区
    memcpy(&fp->outbuffer[fp->out_pos], s, len);
    //更新指针
    fp->out_pos+=len;

    //根据刷新策略决定是否需要刷新
    if(fp->flag == FLUSH_NOW){
        //立即刷新
        write(fp->fileno, fp->outbuffer, fp->out_pos);
        //重置指针
        fp->out_pos = 0;
    }
    else if(fp->flag == FLUSH_LINE){
        //行刷新判断最后一个字符是'\n'
        if(fp->outbuffer[fp->out_pos-1] == '\n'){
            write(fp->fileno, fp->outbuffer, fp->out_pos);
            fp->out_pos = 0;
        }
    }
    else if(fp->flag == FLUSH_ALL){
        //全刷新判断缓冲区是否写满
        if(fp->out_pos == SIZE){
            write(fp->fileno, fp->outbuffer, fp->out_pos);
            fp->out_pos = 0;
        }
    }


    return len;
}

void _fflush(_FILE *fp){
    if(fp->out_pos > 0){
        write(fp->fileno, fp->outbuffer, fp->out_pos);
        fp->out_pos = 0;
    }
}
void _fclose(_FILE *fp){
    if(fp == NULL) return;

    //关闭目标文件时，立即刷新该文件的缓冲区
    _fflush(fp);

    close(fp->fileno);
    free(fp);
}



